
const { http } = uni.$u

// 自定义查询字符串函数，增加参数验证
const getQueryString = (params) => {
  const queryArray = [];
  for (const key in params) {
    if (params.hasOwnProperty(key) && typeof params[key] !== 'undefined') {
      queryArray.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
    }
  }
  return queryArray.join('&');
};

// 显示加载动画
const showLoading = () => {
  uni.showLoading({
    title: '加载中...',
    mask: true
  });
};

// 隐藏加载动画
const hideLoading = () => {
  uni.hideLoading();
};

// 通用的 GET 请求函数
const getRequest = async (url, params) => {
  showLoading();
  const queryString = params ? getQueryString(params) : '';
  const fullUrl = queryString ? `${url}?${queryString}` : url;
  try {
    const response = await http.get(fullUrl);
    return response;
  } catch (error) {
    console.error('Error during GET request:', error);
    throw error;
  } finally {
    hideLoading();
  }
};

// 通用的 POST 请求函数
const postRequest = async (url, data) => {
  showLoading();
  try {
    const response = await http.post(url, data);
    console.log('11111111111111111111', response);
    return response;
  } catch (error) {
    console.error('Error during POST request:', error);
    throw error;
  } finally {
    hideLoading();
  }
};

// 通用的 DELETE 请求函数
const deleteRequest = async (url, params) => {
  showLoading();
  try {
    const queryString = params ? getQueryString(params) : '';
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    const response = await http.delete(fullUrl);
    return response;
  } catch (error) {
    console.error('Error during DELETE request:', error);
    throw error;
  } finally {
    hideLoading();
  }
};

// 通用的 PUT 请求函数
const putRequest = async (url, data) => {
  showLoading();
  try {
    const response = await http.put(url, data);
    return response;
  } catch (error) {
    console.error('Error during PUT request:', error);
    throw error;
  } finally {
    hideLoading();
  }
};

// 导出所有请求函数
export { getRequest, postRequest, deleteRequest, putRequest };